<template>
  <view>
    <view class="head_bank">
      <nut-input v-model="keywords" placeholder="请输入银行名称" @update:model-value="changeInput">
      <template #left>
        <Search></Search>
      </template>
      </nut-input>
    </view>
    <view class="content_bank">
      <nut-elevator :index-list="bankList" @click-item.native="clickItem" @click-index="clickIndex" :height="'100vh'"></nut-elevator>
    </view>
  </view>
</template>

<script setup lang="ts">
import Taro from "@tarojs/taro";
import { ref } from "vue";
import useAddressInfoStore from "../../store/addressbook";
import useUserInfoStore from "../../store/user";
import { $get, $post } from "@/@api/index";
import {pinyin} from 'pinyin-pro'
import {Search} from "@nutui/icons-vue-taro";

const keywords = ref<string>('')
const bankList = ref([])
const allBankList = ref([])

const clickItem = (key: string, item: any) => {
  let pages = Taro.getCurrentPages()
  let prevPage = pages[pages.length - 2]
  prevPage.setData({khName: item.name})
  Taro.navigateBack()
};
const clickIndex = (key: string) => {
  console.log(key)
}

//
const getBankList = async () => {
  const res: any = await $post("/selfmachine-system/banks/list", {});
  if (res.data.code == 200) {
    allBankList.value = transformList(res.data.rows)
    bankList.value = allBankList.value
  } else {
    Taro.showToast({
      icon: 'error',
      title: '加载失败'
    })
  }
}

const transformList = (list:any)=>{
  let arr:any = []
  for(let i=0;i<list.length;i++)
  {
    let firstLetter = (pinyin(list[i].bankName,{ pattern: 'first', toneType: 'none', type: 'array' })[0]).toUpperCase()
    if(arr.length === 0 || arr[arr.length-1].title !== firstLetter){
      arr.push({
        title: firstLetter,
        list: [{...list[i],name:list[i].bankName,id:list[i].btabId}]
      })
    }
    else{
      arr[arr.length-1].list.push({...list[i],name:list[i].bankName,id:list[i].btabId})
    }
  }
  return arr
}

const changeInput = ()=>{
  if(!keywords.value){
    bankList.value = allBankList.value
  }
  else{
    bankList.value = JSON.parse(JSON.stringify(allBankList.value)).filter((item) => {
      item.list = item.list.filter((it)=>{
        return it.name.indexOf(keywords.value) !== -1
      })
      return item.list.length > 0
    })
  }
}

getBankList()

</script>

<style lang="scss">
page {
  --nut-primary-color: #0966ff;
  background-color: #f5f5f5;
}
.nut-elevator__list .nut-elevator__list__fixed__wrapper {
  display: none;
}
.head_bank {

}
.content_bank {
  box-sizing: border-box;
  //padding: 24rpx;
  height: calc(100vh - 90rpx);
  .nut-elevator__list {
    background-color: #fff;
    height: calc(100vh - 90rpx) !important;
    //overflow: hidden !important;
    //height: auto !important;
  }
}
</style>
